<template>
  <div><HomeNavi /></div>
  <div class="background">
    <video
      autoplay
      loop
      muted
      playsinline
      src="@/assets/images/background3.mp4"
      class="background-img"
    >
      Sorry, your browser does not support embedded videos.
    </video>
    <div class="left-text">
      <!--加一个链接到首页-->
      <router-link to="/" active-class="active-link">
        <p style="font-weight: 700">知数ChatBI</p>
      </router-link>
      <p style="font-size: 30px">对话驱动的AI数据分析大模型</p>
      <p style="font-size: 30px">让数据触手可及</p>
    </div>
    <div class="login">
      <a-form class="form" @submit.prevent="handleLogin">
        <a-form-item>
          <span v-if="loginVisible" class="form-title">用户登录</span>
          <span v-if="!loginVisible" class="form-title">用户注册</span>
        </a-form-item>
        <div class="item-login">
          <a-form-item v-bind="validateInfos.username">
            <div class="inputForm">
              <UserOutlined />
              <a-input
                v-model:value="userinfo.username"
                placeholder="用户名"
                style="font-size: 18px"
              />
            </div>
          </a-form-item>
        </div>
        <div class="item-login">
          <a-form-item v-bind="validateInfos.password">
            <div class="inputForm">
              <LockOutlined />
              <a-input-password
                placeholder="密码"
                style="font-size: 18px"
                v-model:value="userinfo.password"
              />
            </div>
          </a-form-item>
        </div>
        <div class="item-login" v-if="loginVisible">
          <a-form-item>
            <div class="flex-row">
              <div>
                <input id="reme" type="checkbox" v-model="rememberMe" />
                <label
                  style="
                    margin-left: 5px;
                    font-size: 17px;
                    font-weight: 500;
                    cursor: pointer;
                  "
                  for="reme"
                  >记住我</label
                >
              </div>
              <span class="span">忘记密码？</span>
            </div>
          </a-form-item>
        </div>
        <div class="item-login" v-if="!loginVisible">
          <a-form-item v-bind="validateInfos.confirm_password">
            <div class="inputForm">
              <LockOutlined />
              <a-input-password
                placeholder="确认密码"
                style="font-size: 18px"
                v-model:value="userinfo.confirm_password"
              />
            </div>
          </a-form-item>
        </div>
        <a-form-item>
          <button v-if="loginVisible" class="button-submit" type="submit">
            登录
          </button>

          <button v-if="!loginVisible" class="button-submit" type="submit">
            注册
          </button>
        </a-form-item>
        <a-form-item>
          <p class="p" v-if="loginVisible">
            没有账号？
            <span class="span" @click="ChangeLoginSingUp">注册账号</span>
          </p>

          <p class="p" v-if="!loginVisible">
            已有账号？
            <span class="span" @click="ChangeLoginSingUp">去登录</span>
          </p>
        </a-form-item>
      </a-form>
    </div>

    <div class="footer-image">
      <a href="https://it.10086.cn/indexc.html" target="_blank">
        <img
          src="@/assets/cmcc.png"
          alt="Footer Image"
          style="max-width: 100%; height: 50px"
        />
      </a>
      <span
        style="font-size: 30px; color: white; margin-left: 1%; margin-right: 1%"
      >
        |
      </span>
      <img
        src="@/assets/svgexport-2.png"
        alt="Footer Image"
        style="max-width: 100%; height: 50px"
      />
    </div>
    <div class="footer-text">
      <p>
        版权所有 © 2024 中国移动信息技术中心·大数据智慧应用中心. 保留所有权利。
      </p>
    </div>
  </div>
</template>

<script setup>
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import HomeNavi from "../components/home/HomeNavi.vue";
import { reactive, ref, onMounted, watch } from "vue";
import { Form, message } from "ant-design-vue";
import { useStore } from "vuex";
import axios from "axios";
import router from "@/router/index";

const store = useStore();
const loginVisible = ref(true);
const userinfo = reactive({
  username: "",
  password: "",
  confirm_password: "",
});

const rememberMe = ref(false);
const error_message = reactive({
  type: 0,
  content: "",
});

function ChangeLoginSingUp() {
  loginVisible.value = !loginVisible.value;
  error_message.content = "";
}

const rules = ref({
  username: [{ required: true, message: "用户名必须" }],
  password: [
    { required: true, message: "密码必须" },
    { min: 8, message: "字符数至少为8" },
    // 添加一个自定义的验证器
    {
      validator: (rule, value) => {
        if (error_message.content !== "") {
          console.log(error_message);
          if (loginVisible) {
            return Promise.reject(new Error(error_message.content));
          }
          return Promise.resolve();
        }
        return Promise.resolve(); // 如果是登录表单，则跳过验证
      },
    },
  ],

  confirm_password: [
    {
      required: loginVisible.value ? false : true,
      message: "确认密码必须填写",
    },
    // 添加一个自定义的验证器
    {
      validator: (rule, value) => {
        if (!loginVisible.value) {
          if (value === userinfo.password) {
            return Promise.resolve();
          }
          return Promise.reject(new Error("两次输入的密码不一致"));
        }
        return Promise.resolve(); // 如果是登录表单，则跳过验证
      },
    },
  ],
});

// 参数1: 待校验的数据 参数2: 校验规则
const { validateInfos, validate } = Form.useForm(userinfo, rules);

const login = () => {
  error_message.content = "";
  store.dispatch("login", {
    // 调用actions中的函数
    username: userinfo.username,
    password: userinfo.password,
    success() {
      router.push({ name: "Conversation" }); //页面跳转
    },
    error() {
      error_message.content = "用户名或密码错误";
      console.log("调用error", error_message.content);
    },
  });
  if (rememberMe.value) {
    let user = {
      username: userinfo.username,
      password: userinfo.password,
    };
    localStorage.setItem("rememberUser", JSON.stringify(user));
  }
};
const register = () => {
  error_message.content = "";

  try {
    axios
      .post("/api/web/register", {
        username: userinfo.username,
        password: userinfo.password,
      })
      .then((response) => {
        if (response.data.token_type === "bearer") {
          console.log("注册成功");
          store.dispatch("login", {
            username: userinfo.username,
            password: userinfo.password,
            success() {
              router.push({ name: "Conversation" });
            },
            error() {
              error_message.content = "系统异常，请稍后重试";
            },
          });
        } else {
          error_message.content = "用户已被注册";
        }
      });
  } catch (error) {
    error_message.content = "网络请求失败，请检查网络连接或稍后再试";
    console.error(error);
  }
};

async function handleLogin(event) {
  await validate();
  // event.preventDefault(); // 阻止默认提交行为
  if (loginVisible.value) {
    login();
  } else {
    register();
  }
}

onMounted(() => {
  const ru = localStorage.getItem("rememberUser");
  // 检查是否有本地存储
  if (ru) {
    // 载入本地存储的用户名
    const rUser = JSON.parse(ru);
    userinfo.username = rUser.username;
    userinfo.password = rUser.password;
  }
});
</script>

<style scoped>
body,
html {
  height: 100%;
  margin: 0;
  padding: 0;
}

.background {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end; /* 右对齐登陆表单 */
}

.background-img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover; /* 确保图片覆盖整个容器且不失真 */
}

.left-text {
  position: absolute;
  top: 30%;
  left: 10%;
  color: rgba(234, 234, 234, 0.9);
  font-size: 90px;
  z-index: 10;
  text-align: left;
}

.left-text a {
  text-decoration: none; /* 移除链接的下划线 */
  color: inherit; /* 继承父元素的颜色 */
}

.login {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 47vw; /* 登陆表单的宽度 */
  height: 100%;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 0px;
  width: 50%; /* 登陆表单的宽度 */
  background: rgba(255, 255, 255, 0.619);
  backdrop-filter: blur(6px);
  padding: 15px 0 0 0;
  border-radius: 20px;
  margin-bottom: 10%;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
.form-title {
  color: rgba(0, 0, 0, 0.7);
  font-size: 16px;
  font-weight: bold;
  font-size: 20px;
}

::placeholder {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.form button {
  align-self: flex-end;
}

.item-login {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flex-column > label {
  color: #151717;
  font-weight: 550;
}

.inputForm {
  width: 19vw;
  border: 1.5px solid #363636;
  border-radius: 10px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding-left: 10px;
  transition: 0.2s ease-in-out;
}

.input {
  margin-left: 10px;
  border-radius: 10px;
  border: none;
  width: 85%;
  height: 100%;
  background-color: transparent;
}

:deep(.inputForm .ant-input) {
  height: 100px;
  border-radius: 10px;
  border: none;
  width: 90%;
  height: 100%;
  background-color: transparent;
}

:deep(.inputForm .ant-input-password) {
  height: 100px;
  border-radius: 10px;
  border: none;
  /* border: 1px solid lawngreen; */
  width: 90%;
  height: 100%;
  background-color: transparent;
}

.inputForm .ant-input:focus-within {
  border: none;
  box-shadow: none;
}

.inputForm .ant-input-password:focus-within {
  border: none;
  box-shadow: none;
}

/* 修改密码输入框内部文本区域的背景颜色 */
:deep(.inputForm .ant-input-affix-wrapper .ant-input) {
  background-color: transparent;
}

.input:focus {
  outline: none;
}

.inputForm:focus-within {
  border: 1.5px solid #2d79f3;
}

.flex-row {
  display: flex;
  height: 50px;
  flex-direction: row;
  align-items: center;
  gap: 5px;
  justify-content: space-between;
}

.flex-row > div > label {
  font-size: 14px;
  color: black;
  font-weight: 400;
}

.span {
  font-size: 17px;
  margin-left: 8vw;
  color: #2d79f3;
  font-weight: 500;
  cursor: pointer;
}

#reme {
  transform: scale(1.2); /* 调整这个值来设置复选框的大小 */
  -webkit-transform: scale(1.2); /* 兼容 Safari 浏览器 */
  -moz-transform: scale(1.2); /* 兼容 Firefox 浏览器 */
  -ms-transform: scale(1.2); /* 兼容 Internet Explorer 浏览器 */
  -o-transform: scale(1.2); /* 兼容 Opera 浏览器 */
  margin: 5px; /* 可选：调整边距以确保复选框不被裁剪 */
}

.button-submit {
  margin: 0 0 0 0;
  background-color: #151717;
  border: none;
  color: white;
  font-size: 15px;
  font-weight: 500;
  border-radius: 10px;
  height: 50px;
  width: 19vw;
  cursor: pointer;
}

.button-submit:hover {
  background-color: #252727;
}

.p {
  text-align: center;
  color: black;
  font-size: 17px;
  margin: 5px 0;
}

.footer-image {
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 20; /* 确保它在所有其他元素之上 */
  display: flex;
  justify-content: center; /* 图片居中 */
  margin-bottom: 50px;
}

.footer-image img {
  max-width: 100%;
  height: auto;
}

.footer-text {
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 20; /* 确保它在所有其他元素之上 */
  display: flex;
  justify-content: center; /* 图片居中 */
  margin-bottom: 1px;
}

.footer-text p {
  font-size: 14px;
  color: rgb(184, 184, 184);
  text-align: center;
}
</style>
